<template>
  <div id="mapContainer" />
</template>

<script>
import { province } from 'assets/area_data/province'
import { city } from 'assets/area_data/city'
import { county } from 'assets/area_data/county'

import 'assets/mapvgl/mapvgl.min.js'

import { zoomRange, getOpacityNum, getRandomNum } from '../tools/index'

export default {
  name: 'BaiduMapGl',
  props: {
    mapAttrs: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      map: null,
      mapGrade: null, // 地图等级
      bd: null, // 创建行政区域搜索对象
      maskProvince: {}, // 当前省级蒙层对象
      zoomCityLeve: null // 当前缩放区的市等级
    }
  },
  mounted() {
    this.map = this.initMap({
      center: [106.683, 33.033],
      zoom: 4.5,
      enableDblclickZoom: false, // 是否开启双击放大功能
      style: {
        styleId: '39a71d0a7a1434a5941b66816f057af7'
      }
    })

    this.renderingMap(province, 'province')

    this.map.addEventListener('zoomend', this.listenZoomEnd)
    this.$on('hook:destroyed', () => {
      window.removeEventListener('zoomend', this.listenZoomEnd)
    })
  },
  methods: {
    renderingMap(areaArr, areaType) {
      this.mapGrade = areaType
      let that = this
      areaArr.forEach(item => {
        let currentAreaName = item.name === '市辖区' ? item.province : item.name
        if (!currentAreaName) return

        this.bd.get(currentAreaName, function(rs) {
          // let fillColor = ['#29B6F6', '#5C6BC0', '#42A5F5', '#26C6DA', '#66BB6A', '#8D6E63']
          // let randomNum = Math.abs(Math.floor(Math.random() * 10 - 4))

          let areaAttrObj = {
            id: item.id,
            type: that.mapGrade,
            name: currentAreaName
          }
          try {
            let currentHole = that.showPoly(rs, '#42A5F5', areaAttrObj) // transparent fillColor[randomNum]
            // 鼠标移入
            currentHole.addEventListener('onmouseover', that.listenHoleMove)
            // 鼠标移入出
            currentHole.addEventListener('onmouseout', that.listenHoleOut)
            // 鼠标点击
            currentHole.addEventListener('onclick', that.listenHoleClick)
          } catch (e) {
            console.warn(currentAreaName, '百度地图未搜索到当前区域，无法渲染蒙层')
          }
        })
      })
    },
    listenHoleMove(params) {
      let currentTarget = params.target
      currentTarget.setFillColor('#5C6BC0')
    },
    listenHoleOut(params) {
      let currentTarget = params.target
      currentTarget.setFillColor(currentTarget.originalColor)
    },
    listenHoleClick(params) {
      let currentTarget = params.target
      // 地图信息展示
      let mapArea = {
        name: currentTarget.currentAreaName,
        id: currentTarget.currentAreaId,
        type: currentTarget.currentAreaType
      }
      this.showMapPanelView(mapArea)

      // 获取当前区域边界
      let bounds = currentTarget.getBounds()
      let maxX = bounds.maxX
      let maxY = bounds.maxY
      let minX = bounds.minX
      let minY = bounds.minY
      let centerX = minX + (maxX - minX) / 2
      let centerY = minY + (maxY - minY) / 2
      let difference = (maxX - minX) > (maxY - minY) ? (maxX - minX) : (maxY - minY)
      let differenceNum = difference.toFixed(2)
      // 缩放比： 上海10  北京9.5  银川8.5   河南8  成都7.5  拉萨/哈尔滨/海口 7       乌鲁木齐6.5
      // latLng差值  1.42   2.09    4.15   6.28    11.19    20.68 / 13.88 / 16.54     22.86

      let zoomNum = zoomRange(differenceNum)

      // 渲染二级蒙层
      if (this.mapGrade === 'province') {
        this.maskProvince = {
          name: city[currentTarget.currentAreaId][0].province,
          id: currentTarget.currentAreaId,
          type: 'province'
        }
        // eslint-disable-next-line no-undef
        this.map.flyTo(new BMapGL.Point(centerX, centerY), zoomNum)
        this.renderingMap(city[currentTarget.currentAreaId], 'city')
      } else if (this.mapGrade === 'city') {
        this.zoomCityLeve = this.map.getZoom()
        // eslint-disable-next-line no-undef
        this.map.flyTo(new BMapGL.Point(centerX, centerY), zoomNum)
        this.renderingMap(county[currentTarget.currentAreaId], 'county')
      } else {
        // eslint-disable-next-line no-undef
        this.map.panTo(new BMapGL.Point(centerX, centerY))
        console.warn('当前蒙层是' + this.mapGrade + '，禁止放大')
        return false
      }
      this.map.clearOverlays()
    },
    listenZoomEnd(params) {
      let currentTarget = params.target
      if (currentTarget.zoomLevel <= 5.5 && this.mapGrade !== 'province') {
        this.map.clearOverlays()
        this.mapGrade = 'province'
        this.renderingMap(province, 'province')
        // TEST: id需要在实际项目中改为全国
        this.showMapPanelView({ name: '全国', id: '000' })
      } else if (currentTarget.zoomLevel <= this.zoomCityLeve && this.mapGrade === 'county') { // || (params.target.zoomLevel >= 6 && mapGrade === 'province')
        this.map.clearOverlays()
        this.mapGrade = 'city'
        this.renderingMap(city[this.maskProvince.id], 'city')

        this.showMapPanelView(this.maskProvince)
      }
    },
    showPoly(rs, color, areaAttrObj) {
      // eslint-disable-next-line no-undef
      let hole = new BMapGL.Polygon(rs.boundaries, { // 创建多边形覆盖物
        fillColor: color,
        fillOpacity: getOpacityNum(),
        strokeColor: '#fff', // 边线颜色
        strokeWeight: 2,
        strokeOpacity: 1
      })
      hole.originalColor = color // 记录原始颜色
      hole.currentAreaId = areaAttrObj.id // 记录当前区域ID
      hole.currentAreaType = areaAttrObj.type
      hole.currentAreaName = areaAttrObj.name
      this.map.addOverlay(hole)
      return hole
    },
    initMap(options) {
      options = Object.assign({
        tilt: 0,
        heading: 0
      }, options)
      // eslint-disable-next-line no-undef
      let map = new BMapGL.Map('mapContainer', {
        restrictCenter: false,
        style: options.style
      })
      map.enableScrollWheelZoom() // 允许地图可被鼠标滚轮缩放，默认禁用
      map.enableKeyboard() // 启用键盘操作
      map.enableInertialDragging() // 启用地图惯性拖拽
      map.setMinZoom(4) // 最小缩放等级
      map.setMaxZoom(14) // 最大缩放等级
      // eslint-disable-next-line no-undef
      this.bd = new BMapGL.Boundary() // 创建行政区域搜索对象

      map.setDisplayOptions(options.displayOptions || {
        indoor: false,
        building: false,
        poi: true,
        skyColors: options.skyColors || [
          'rgba(5, 5, 30, 0.01)',
          'rgba(5, 5, 30, 1.0)'
        ]
      })
      if (options.center && options.zoom) {
        // eslint-disable-next-line no-undef
        map.centerAndZoom(new BMapGL.Point(options.center[0], options.center[1]), options.zoom)
      }

      map.setTilt(options.tilt)
      map.setHeading(options.heading)
      return map
    },
    showMapPanelView(obj) {
      let randomID = getRandomNum() // 随机ID生成
      obj.id = randomID
      this.$emit('changeMapInfo', obj)

      // mapInfo.clearIntervalNum = clearInterval(mapInfo.clearIntervalNum)
      // mapInfo.totalArr = []
      // mapInfo.isFirstLoad = true
      // mapInfo.currentCount = 0
      // mapInfo.reboundCount = 0
      // // mapInfo.currentPage = 1;
      // $('#mapInfoContent').html('')
      // mapPanelView.id = this.getRandomNum()
      // getMapInfoData(mapPanelView.id) // 显示地图区域信息
      // getAreaClassifyData(mapPanelView.id) // 显示区域分类
    }
  }
}
</script>

<style lang="scss">
#mapContainer {
  width: 100%;
  height: 56.7vh;
  position: relative;
  left: 1px;
  z-index: 3;
  opacity: 0.9;
  background-image:unset !important;
}

/* 清除百度地图logo */
.anchorBL {
  display: none;
}
</style>
